//
//  HYQViewController.m
//  HYQPlayer
//
//  Created by zxj1989 on 07/13/2018.
//  Copyright (c) 2018 zxj1989. All rights reserved.
//

#import "HYQViewController.h"
#import "AliyunVodPlayerView.h"

#define videoID @"e61da58f36514e8c9d85d41b41ccd03c"

#define ScreenWidth CGRectGetWidth([[UIScreen mainScreen] bounds])
#define ScreenHeight CGRectGetHeight([[UIScreen mainScreen] bounds])

@interface HYQViewController ()

@property (nonatomic, strong) AliyunVodPlayerView *playerView;
@property (nonatomic, assign) BOOL isLock;

@end

@implementation HYQViewController

- (AliyunVodPlayerView *)playerView
{
    if (!_playerView) {
        CGFloat width = 0;
        CGFloat height = 0;
        CGFloat topHeight = 0;
        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
        if (orientation == UIInterfaceOrientationPortrait ) {
            width = CGRectGetWidth([[UIScreen mainScreen] bounds]);
            height = ScreenWidth * 9 / 16.0;
            topHeight = 20;
        }else{
            width = ScreenWidth;
            height = CGRectGetHeight([[UIScreen mainScreen] bounds]);
            topHeight = 20;
        }
        /****************UI播放器集成内容**********************/
        _playerView = [[AliyunVodPlayerView alloc] initWithFrame:CGRectMake(0,topHeight, width, height) andSkin:AliyunVodPlayerViewSkinRed];
        //        _playerView.circlePlay = YES;
        [_playerView setDelegate:self];
        [_playerView setAutoPlay:YES];
        _playerView.isNeedShare = YES;
        
        [_playerView setPrintLog:YES];
        
        _playerView.isScreenLocked = false;
        _playerView.fixedPortrait = false;
        self.isLock = self.playerView.isScreenLocked||self.playerView.fixedPortrait?YES:NO;
        
        //边下边播缓存沙箱位置
        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [pathArray objectAtIndex:0];
        //maxsize:单位 mb    maxDuration:单位秒 ,在prepare之前调用。
        [_playerView setPlayingCache:NO saveDir:docDir maxSize:300 maxDuration:10000];
    }
    return _playerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.playerView];
    
    [self getAccessCompleted:^(NSString *accessKey, NSString *accessKeySecret, NSString *accessToken, NSString *expireTime) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.playerView playViewPrepareWithVid:videoID accessKeyId:accessKey accessKeySecret:accessKeySecret securityToken:accessToken];
        });
    }];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationBecomeActive) name:UIApplicationWillResignActiveNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(becomeActive)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(resignActive)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
}

- (void)becomeActive{
    if (self.playerView && self.playerView.playerViewState == AliyunVodPlayerStatePause){
        [self.playerView start];
    }
    
}

- (void)resignActive{
    if (self.playerView && self.playerView.playerViewState == AliyunVodPlayerStatePlay){
        [self.playerView pause];
    }
}

- (void)applicationEnterBackground
{
    [_playerView pause];
}

- (void)applicationBecomeActive
{
    [_playerView resume];
}

- (void)getAccessCompleted:(void(^)(NSString *accessKey, NSString *accessKeySecret, NSString *accessToken, NSString *expireTime))completed
{
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.hotyq.com:9999/api/0685/aliyun/getToken.do?app_os=ios"]];
    [NSURLConnection sendAsynchronousRequest:req queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        if (!connectionError) {
            NSError *error = nil;
            id res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
            NSDictionary *modelObject = res[@"data"];
            NSLog(@"%@",modelObject);
            if ([modelObject count]) {
                NSString *accessKey = modelObject[@"accessKeyId"];
                NSString *accessSecret = modelObject[@"accessKeySecret"];
                NSString *accessToken = modelObject[@"securityToken"];
                NSString *expireTime = modelObject[@"expriedTime"];
                
                accessToken = [self base64DecodeWithString:accessToken];
                
                if ([accessToken hasSuffix:accessSecret]) {
                    accessToken = [accessToken stringByReplacingOccurrencesOfString:accessSecret withString:@""];
                    if (completed) {
                        completed(accessKey,accessSecret,accessToken,expireTime);
                    }
                }
            }
        }
    }];
}

- (NSString *)base64DecodeWithString:(NSString *)base64String;
{
    NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    return string;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
